package top.lileix.example.netty.chat;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author lilei
 *
 */
public class ChatClient {
	public String inetHost;
	public int inetPort;

	public ChatClient(String inetHost, int inetPort) {
		super();
		this.inetHost = inetHost;
		this.inetPort = inetPort;
	}

	public static void main(String[] args) {
		ChatClient client = new ChatClient("172.16.8.36", 1017);
		client.run();
	}

	public void run() {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					// 解码
					pipeline.addLast("DelimiterBasedFrameDecoder",
							new DelimiterBasedFrameDecoder(8129, Delimiters.lineDelimiter()));
					// 解码
					pipeline.addLast("解码", new StringDecoder());
					// 编码
					pipeline.addLast("编码", new StringEncoder());
					pipeline.addLast(new ChatClientHandler());
				}

			});

			Channel ch = bootstrap.connect(inetHost, inetPort).sync().channel();
			// 输入
			BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
			// 最后发送消息的通道
			ChannelFuture lastWriteFuture = null;
			while (true) {
				String msg = in.readLine();
				if (msg == null) {
					break;
				}
				System.out.println("msg:" + msg);
				lastWriteFuture = ch.writeAndFlush(msg + "\r\n");
				System.out.println("发送完毕");
				if ("exit".equals(msg)) {
					ch.closeFuture().sync();
					break;
				}
			}
			// 等到所有消息刷新之前关闭通道。
			if (lastWriteFuture != null) {
				lastWriteFuture.sync();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
}
